package com.example.client_group5;

import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.base.AppBaseActivity;

import eu.erikw.PullToRefreshListView;
import eu.erikw.PullToRefreshListView.OnRefreshListener;

import util.HttpClientFactory;






import android.os.Bundle;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;


import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;


public class FollowerActivity extends AppBaseActivity {
	int itemsPerPage = 6;
	boolean loadingMore = false;
	boolean loadingHead = false;
	private ArrayList<User> users;
	private UserItemAdapter adapter;
	private int max_id = -1;
	private int since_id=-1;
	private int user_id=1;
	private PullToRefreshListView listView;
	private View footerView;
	private TextView title;
	String[] infor;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_follow);
        registerBaseActivityReceiver();
        Bundle b = getIntent().getExtras();
        infor = b.getStringArray("owner");
        user_id = Integer.parseInt(infor[0]);
        title=(TextView)findViewById(R.id.title);
        title.setText("Follower");
        this.listView = (PullToRefreshListView)findViewById(R.id.ListViewId);
       // ArrayList<User> users = getFollower(user_id);
        users=new ArrayList<User>();
        adapter=new UserItemAdapter(this, R.layout.listfollowing, users);
        
        footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
        listView.addFooterView(footerView);
        listView.setAdapter(adapter);
        listView.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				
				Log.d("tag","loading first....");
				Thread thread=new Thread(null,loadFirstListItems);
				thread.start();	
			}
		});
        listView.setOnScrollListener(new OnScrollListener() {
			
        	//useless here, skip!
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
			
			}
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				//what is the bottom item that is visible
				int lastInScreen = firstVisibleItem + visibleItemCount;				
				Log.d("tag", "lastInScreen: " + lastInScreen + "/ totalItemCount: " + totalItemCount);
				//is the bottom item visible & not loading more already ? Load more !
				if((lastInScreen == totalItemCount) && !(loadingMore)){
					Log.d("tag", "Loading more item...........");
					loadingMore = true;
					Thread thread =  new Thread(null, loadMoreListItems);
			        thread.start();
				}
			}
		});
//        listView.setOnItemClickListener(new OnItemClickListener() {
//        	@Override
//			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
//					long arg3) {
//				// TODO Auto-generated method stub
//				
//				if(arg2 >= 1){
//					
//					User user = adapter.getItem(arg2 - 1);
//					Intent i = new Intent(FollowerActivity.this, ProfileActivity.class);
//					Bundle b = new Bundle();
//					String [] info={Integer.toString(user.id),user.user_fullname,
//							user.user_name,user.avatar,"home"};
//					b.putStringArray("user", info);
//					i.putExtras(b);
//					startActivity(i);
//					finish();
//				}
//			}
//        });
        title.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				closeAllActivities();
			}
		});
        
        View tweetButton = (View)findViewById(R.id.btTweet);
        tweetButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(FollowerActivity.this, TweetActivity.class);
				Bundle b = new Bundle();
				String[] replyInfo = {"follow"};
				b.putStringArray("reply", replyInfo);
				i.putExtras(b);
				startActivity(i);
//				finish();
			}
		});
    }
     
    public ArrayList<User> getFollower(int user_id,int count){
    	//
    	
    	String getUrl = Setting.ipServer + "api/user/get-followers/user_id/"+user_id;
    	if(max_id == -1 && since_id==-1)
    		getUrl += "/count/" + count;
    	else if(max_id!=-1)
    		getUrl += "/max_id/" + max_id + "/count/" + count;
    	else if(since_id!=-1)
    		getUrl += "/count/" + count +"/since_id/"+since_id;
    	ArrayList<User> users=new ArrayList<User>();
    	//HttpClient client=new DefaultHttpClient();
    	HttpClient client=HttpClientFactory.getThreadSafeClient();
    	HttpGet get=new HttpGet(getUrl);
    	ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();
		String responseBody = null;
		try {
		    responseBody = client.execute(get, responseHandler);
		    
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		Log.d("tag", "Tra ve: " + responseBody);
		//JSONObject jsonObject = null;
		JSONArray userArray=null;
		try{
			
			userArray=new JSONArray(responseBody);
			Log.d("tag", userArray.toString());
			
			for(int i=0;i<userArray.length();i++)
			{
				JSONObject userItem=userArray.getJSONObject(i);
				int id=userItem.getInt("id");
				boolean is_following=userItem.getBoolean("is_following");
				String user_name=userItem.get("username").toString();
				String user_fullname=userItem.get("fullname").toString();
				String avatar=userItem.get("avatar").toString();	
				users.add(new User(id,user_name, user_fullname, avatar, 0, 0, 0,false,
						is_following,false,"",""));
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return users;
    }
    
    private Runnable loadFirstListItems = new Runnable() {
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		loadingHead=true;
    		try{
    			Thread.sleep(1000);
    		}catch(InterruptedException e){
    			e.printStackTrace();
    		}
    		users = new ArrayList<User>();
    		max_id=-1;
    		if(adapter.getCount()>0)
    			since_id=adapter.getItem(0).id;
        	users = getFollower(user_id,itemsPerPage);

        	

    		//Done! now continue on the UI thread
            runOnUiThread(returnResult);
    	}
    };
    private Runnable returnResult=new Runnable() {
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		if(users!=null && users.size()>0)
    		{
    			for(int i=0;i<users.size();i++)
    				adapter.insert(users.get(i), 0);
    		}
    		//Log.d("tag","since_id :"+since_id);
    		adapter.notifyDataSetChanged();
    		listView.onRefreshComplete();
    		/*if(tweets.size() > 0)
    			loadingHead=false;
    		else
    			listView.removeHeaderView(headerView);*/
    	}
    };
    
    //Runnable to load the items 
    private Runnable loadMoreListItems = new Runnable() {			
		@Override
		public void run() {
			//Set flag so we cant load new items 2 at the same time
			//loadingMore = true;
	    	try{
	    		Thread.sleep(1000);
	    	}catch(InterruptedException e){}
	    	users = new ArrayList<User>();
	    	since_id=-1;
	    	if(adapter.getCount()>0)
	    		max_id=adapter.getItem(adapter.getCount()-1).id;
	    	users = getFollower(user_id,itemsPerPage);
	    //	Log.d("tag", "size of tweets: " + tweets.size());
//	    	if(users.size() > 0){
//	    		max_id = users.get(users.size() - 1).id;
//	    		Log.d("tag", "max id: " + max_id);
//	    	}
	    	
			//Done! now continue on the UI thread
	        
	    	runOnUiThread(returnRes);
	        
		}
	};	
	//Since we cant update our UI from a thread this Runnable takes care of that! 
    private Runnable returnRes = new Runnable() {
        @Override
        public void run() {
        	if(users != null && users.size() > 0){
        		for(int i = 0; i < users.size(); i ++){
        			adapter.add(users.get(i));
        		}
        	}
        	Log.d("tag", "Adapter size: " + adapter.getCount());
        	//Update the Application title
        	//setTitle("Neverending List with " + String.valueOf(adapter.getCount()) + " items");
        	//Tell to the adapter that changes have been made, this will cause the list to refresh
            adapter.notifyDataSetChanged();
            //listView.setAdapter(adapter);
			//Done loading more.
            if(users.size() > 0)
            	loadingMore = false;
            else
            	listView.removeFooterView(footerView);
        }
    };
    public boolean onKeyDown(int keyCode, KeyEvent event){
		if(keyCode == KeyEvent.KEYCODE_BACK){
//			Intent i = new Intent(FollowerActivity.this, ProfileActivity.class);
//			Bundle b = new Bundle();
//			b.putStringArray("user", infor);
//			i.putExtras(b);
//			startActivity(i);
			finish();
		}
		return false;
		
	}
    public void onDestroy(){
    	super.onDestroy();
    	unRegisterBaseActivityReceiver();
    	System.gc();
    }

}

  
